package com.livefilms.main;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpConnect {
	
	private static Logger log = Logger.getLogger(HttpConnect.class);
	private static Logger log_error = Logger.getLogger("ERROR");
	
	public static String URL_INFO = "http://livefilms.altervista.org/www/integration/Ingestion/AddInfo.php"; 
	public static String URL_URL  = "http://livefilms.altervista.org/www/integration/Ingestion/AddUrl.php";
	public static String URL_IMAGE  = "http://livefilms.altervista.org/www/integration/Ingestion/AddImage.php";
	
	public NameValuePair[] setDataCineModel(CineModel model){

		NameValuePair[] data = {
		          new NameValuePair("ID", new String(String.valueOf(model.getId()))),
		          new NameValuePair("TT", new String(String.valueOf(model.getTitolo()))),
		          new NameValuePair("DS", new String(String.valueOf(model.getDescrizione()))),
		          new NameValuePair("TP", new String(String.valueOf(model.getTipologia()))),
		          new NameValuePair("US", new String(new SimpleDateFormat("yyyy-MM-dd").format(model.getDataUscita()).trim())),
		          new NameValuePair("DR", new String(String.valueOf(model.getDurata()))),
		          new NameValuePair("AA", new String(String.valueOf(model.getAnno()))),
		          new NameValuePair("SB", new String(String.valueOf(model.isSub()))),
		          new NameValuePair("BN", new String(String.valueOf(model.isBn()))),
		          new NameValuePair("LC", new String(String.valueOf(model.getLocandina()))),
		          new NameValuePair("PS", new String(String.valueOf(model.getPaese())))
		        };
		
		return data;
		
	}
	
    public NameValuePair[] setUrls(Urls url){
		
		NameValuePair[] data = {
		          new NameValuePair("ID", new String(String.valueOf(url.getId()))),
		          new NameValuePair("UR", new String(String.valueOf(url.getUrl()))),
		          new NameValuePair("NM", new String(String.valueOf(url.getHost()))),
		          new NameValuePair("TP", new String(String.valueOf(url.getType())))
		        };
		
		return data;
		
	}
    
    public NameValuePair[] setImage(long ID , byte[] data_image,String url){
    	NameValuePair[] data = {
    			 new NameValuePair("ID", new String(String.valueOf(ID))),
    			 new NameValuePair("BYTE",new String(Base64.encodeBase64(data_image))),
    			 new NameValuePair("URL", new String(String.valueOf(url)))
    	};
		return data;
    }
	
	public void  callhttp(String url,NameValuePair[] data){
		log.debug("==== CALL URL ====");
		PostMethod post = new PostMethod(url);
		post.addRequestHeader("User-Agent", "Mozilla/5.0");
        post.setRequestBody(data);
        HttpClient client = new HttpClient();
        client.getParams().setCookiePolicy("compatibility");
        BufferedReader in = null;
        log.debug("BufferedReader:"+url);
        try {
            int status = client.executeMethod(post);
            log.debug("Status:"+ status);
			in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
			String body = new String();
			while ((body = in.readLine()) != null) {
				if(!body.trim().contains("OK") && !body.isEmpty()){
					log.info(body.trim());
				}
			}
			
		} catch (IOException e) {
			log_error.error(e);
			e.printStackTrace();
		}finally{
			if(in !=null){
				try {
					in.close();
				} catch (IOException e) {
					log_error.error(e);
					e.printStackTrace();
				}
			}
		}
        
	}
	
	public void callLocandina(CineModel model){

		try {
			URL url = new URL(model.getLocandina().replace(" ","%20"));
			InputStream in = new BufferedInputStream(url.openStream());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int n = 0;
			while (-1!=(n=in.read(buf))){
			   out.write(buf, 0, n);
			}
			out.close();
			in.close();
			byte[] response = out.toByteArray();
			HttpUtility utility = new HttpUtility();
			response = utility.scale(response,155, 200);
			callhttp(HttpConnect.URL_IMAGE,setImage(model.getId(),response,model.getLocandina()));
			
		} catch (IOException e) {
			log_error.error(e);
			e.printStackTrace();
		}
	}

}
